<template>
  <k-view class="rank-page">
    <top-banner :title="pageTitle" :titleTip="blockTypeName" :subTitle="pageSubTitle"></top-banner>
    <k-view class="content-view">
      <rank-table
        :data="data"
        :requestData="tableData"
        :globalLoading="isLoading"
        :isShowNoData="isEmpty"
        @click-row="clickRow"
        @tableSort="tableSort"
        @toBottom="toBottomThrottle"
        :customSort="customSort"
        :themeType="'mobile-app-' + theme"
      ></rank-table>
    </k-view>
  </k-view>
</template>

<script>
import topBanner from '../../components/Home/topBanner.vue';
import pageTabs from '../../components/Home/pageTabs.vue';
import { getRankingList } from '@/apis';
import Apis from '@king-fisher/apis';
import { changeStringIntoDate, getUrlSearch, jumpByUrl, jumpToFenshi, setCookie } from '@/utils';
import { tableHeaderData } from '@/config/tableHeader';
import { sendClickStat, sendPageStat } from '@/utils/stat';
import { PAGEID } from '@/config/stat';
import { debounce, throttle } from '../../utils/index';
import themeMixin from '../../mixins/themeMixin';
import rankReload from '@/components/Home/rankReload.vue';

// type rank_params = {
//   block_type: string;
//   stock_codes?: string;
//   block_code?: string;
//   page_size: string;
//   page_num: string;
//   sort_field: string;
//   sort_mod: string;
// };
export default {
  components: {
    topBanner,
    pageTabs,
    rankReload,
  },
  data() {
    return {
      text: '表格',
      activeTab: 1,
      pageTitle: '健康指数排行榜',
      data: tableHeaderData,
      pageSubTitle: '更新时间 ',
      tableData: [],
      originData: [],
      customSort: true,
      block_type: '',
      block_code: '',
      block_name: '',
      page_size: '20',
      page_num: '0',
      sort_field: 'composite_score',
      sort_way: 'desc',
      lastParams: '',
      lastapi: '',
      isLoading: false,
    };
  },
  mixins: [themeMixin],
  methods: {
    getRankingData: debounce(async function (params, api, reload) {
      let timer;
      let realParams;
      let realApi;
      const timeout = new Promise((resolve, reject) => {
        timer = setTimeout(() => {
          reject('请求超时!');
        }, 5000);
      });
      if (reload) {
        realApi = this.lastapi;
        realParams = this.lastParams;
      } else {
        realApi = api;
        realParams = params;
      }
      Promise.race([timeout, realApi(realParams)])
        .then(res => {
          if (res.status_code !== 0) {
            Apis.Toast.show('暂未查询到相关信息');
            return;
          }
          const dataList = res.data?.list || [];
          this.tableData = this.tableData.concat(
            dataList.map(item => {
              return {
                stock_name: item.name,
                stock_code: item.code,
                composite_score: item.composite_score.toFixed(2),
                nervous_score: item.nervous_score.toFixed(2),
                motor_score: item.motor_score.toFixed(2),
                secretion_score: item.secretion_score.toFixed(2),
                immune_score: item.immune_score.toFixed(2),
                respiratory_score: item.respiratory_score.toFixed(2),
                circulatory_score: item.circulatory_score.toFixed(2),
                urinary_score: item.urinary_score.toFixed(2),
                digesive_score: item.digesive_score.toFixed(2),
                reproductive_score: item.reproductive_score.toFixed(2),
                market: item.market,
              };
            })
          );
          if (this.activeTab === 2) {
            this.pageSubTitle = `更新时间：${getCurrentDate()}`;
          } else {
            this.pageSubTitle = `更新时间：${changeStringIntoDate(res.data?.report_date)}`;
          }
          this.originData = this.originData.concat(dataList);
          if (dataList.length != 0) {
            this.page_num = String(Number(this.page_num) + 1); //每次滚动page_num+1
          }
        })

        .finally(() => {
          this.isLoading = false;
          this.lastParams = realParams;
          this.lastapi = realApi;
          clearTimeout(timer);
        });
    }, 100),
    /**
     * Description
     * @param { {
  block_type: string;
  stock_codes?: string;
  block_code?: string;
  page_size: string;
  page_num: string;
  sort_field: string;
  sort_mod: string;
}} params
     * @returns {any}
     */
    async getRankingListData(params) {
      this.getRankingData(params, getRankingList);
    },
    clickRow(row, column) {
      const stockIndex = this.originData.findIndex(item => {
        return item.code === row.stock_code;
      });
      if (stockIndex !== -1) {
        const stockItem = this.originData[stockIndex];
        if (stockItem) {
          if (column.type === 'stock') {
            //跳转个股分时
            sendClickStat(`${PAGEID.RANK}.stocks.${row.stock_code}.${stockIndex + 1}.click`);
            jumpToFenshi(row.stock_code, stockItem.market, stockItem.name);
          } else {
            //跳转个股诊断
            sendClickStat(`${PAGEID.RANK}.bmidetails.${row.stock_code}.${stockIndex + 1}.click`);
            jumpByUrl({
              name: 'stock',
              query: {
                stockCode: row.stock_code,
                market: stockItem.market,
                stockName: row.stock_name,
              },
            });
          }
        }
      }
    },
    tableSort(key, sortWay) {
      //初始化,page
      this.page_num = '0';
      this.isLoading = true;
      this.tableData = [];
      this.originData = [];
      const params = {
        block_type: this.block_type,
        page_size: this.page_size,
        page_num: '0',
        sort_field: key,
        sort_mod: sortWay,
        block_code: this.block_code,
      };
      this.getRankingListData(params);
    },
    toBottom() {
      const params = {
        block_type: this.block_type,
        page_size: this.page_size,
        page_num: this.page_num,
        sort_field: this.sort_field,
        sort_mod: this.sort_way,
        block_code: this.block_code,
      };
      this.getRankingListData(params);
    },
    reload() {
      this.isLoading = true;
      this.getRankingData(null, null, true);
    },
  },
  created() {
    const query = getUrlSearch();
    this.block_type = query.block_type;
    this.block_code = query.block_code;
    const tipName = query.block_name || '';
    this.block_name = decodeURIComponent(tipName);

    const params = {
      block_type: this.block_type,
      page_size: this.page_size,
      page_num: this.page_num,
      sort_field: this.sort_field,
      sort_mod: this.sort_way,
      block_code: this.block_code,
    };
    this.isLoading = true;
    this.getRankingListData(params);
    this.toBottomThrottle = throttle(this.toBottom, 1000);
  },
  mounted() {
    setCookie().then(id => {
      sessionStorage.setItem('userIdKey', id);
      sendPageStat(`${PAGEID.RANK}_${this.block_type === 'industry' ? 'field' : 'area'}`);
    });
  },
  computed: {
    blockTypeName() {
      const typeMap = {
        industry: '行业',
        region: '地区',
      };
      return this.block_type in typeMap ? this.block_name + typeMap[this.block_type] : '';
    },
    isEmpty() {
      return this.tableData.length === 0;
    },
  },
};
</script>

<style lang="less">
.rank-page {
  width: 100%;
  height: 100%;
  .content-view {
    width: 100%;
    height: 100%;
  }
}
[theme-mode='black'] {
  .rank-page {
    background-color: #1c1c1c;

    .content-view {
      background-color: #1c1c1c;
    }
  }
}
.hxm-table {
  z-index: 0 !important;
}
</style>
